<template>
  <!-- 弹框-->
  <a-modal
    :title="$t('all.autotext512')"
    :visible="innerVisible"
    @cancel="clickCancel"
    @ok="clickConfirm"
    width="50%"
    :confirmLoading="confirmLoading"
  >
    <a-form-model
      ref="ruleForm"
      :rules="rules"
      :model="form"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      labelAlign="left"
    >
      <a-form-model-item :label="$t('all.autotext695')" prop="personalApply" style="width: 90%;">
        <a-radio-group v-model="needApply" >
          <a-radio :value="1">{{ $t('all.autotext662') }}</a-radio>
          <a-radio :value="0">{{ $t('all.autotext516') }}</a-radio>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item
        v-if="needApply == 1"
        :label="$t('all.autotext1485')"
        prop="personalTax"
        style="width: 90%;"
      >
        <a-input
          v-model="form.personalTax"
          :placeholder="$t('all.autotext1146')"
          :min="0.01"
          :precision="2"
          @input="(e) => (this.form.personalTax = moneyCheck(e.target.value))"
          style="width: 90%;"
        />
      </a-form-model-item>
      <a-form-model-item
        v-if="needApply == 1"
        :label="$t('all.autotext948')"
        prop="approveDate"
        style="width: 90%;"
      >
        <a-date-picker
          v-model="form.approveDate"
          :placeholder="$t('all.autotext763')"
          format="YYYY-MM-DD"
          valueFormat="YYYY-MM-DD"
          style="width: 90%;"
        />
      </a-form-model-item>
      <a-form-model-item
        v-if="needApply == 1"
        :label="$t('all.autotext1194')"
        prop="taxUrl"
        style="width: 90%;"
      >
        <div class="upload-tax-item clearfix">
          <div>{{ $t('all.autotext276') }}：PNG/JPG</div>
          <a-upload
            accept=".jpg, .jpeg, .png"
            :beforeUpload="beforeUpload"
            :showUploadList="false"
            :customRequest="e => handleUpload(e)"
          >
            <!-- <div v-if="fileList.length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">
                Upload
              </div>
            </div> -->
            <a-button type="primary" :loading="uploading" v-if="fileList.length < 1">
              <a-icon type="upload" />
              {{ $t('all.autotext1324') }}
            </a-button>
          </a-upload>
          <div v-if="fileList.length" class="upload-btn">
            <div>
              <img
                style="width:200px;height:100px;"
                :src="$options.filters.dealImageUrl(fileList[0].afterUrl || fileList[0].originalUrl)"
              />
            </div>
            <a-space>
              <a type="link" @click="handlePreview">{{ $t('all.autotext84') }}</a>
              <template v-if="desensePassed">
                <a type="link" @click="editFile">{{ $t('all.autotext1231') }}</a>
                <a type="link" @click="resetFile">{{ $t('all.autotext1691') }}</a>
                <a-popconfirm :title="$t('all.autotext688')" @confirm="deleteFile">
                  <a>{{ $t('all.autotext379') }}</a>
                </a-popconfirm>
              </template>
              <template v-else>
                <a type="link" @click="editFile">{{ $t('all.autotext236') }}</a>
              </template>
            </a-space>
          </div>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
            <img
              :key="previewImage"
              alt="example"
              style="width: 100%"
              :src="previewImage | dealImageUrl"
            />
          </a-modal>
        </div>
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext983')" style="width: 90%;" prop="taxRemark" >
        <a-input
          type="textarea"
          v-model="form.taxRemark"
          :placeholder="needApply == 1 ? $t('all.autotext1000') : $t('all.autotext486') "
          style="width: 90%;"
        />
      </a-form-model-item>
    </a-form-model>
    <DesensitizationModal
      ref="desensitization"
      v-bind="{...desensDialog}"
      @ok="handleDesensDialogOk"
      @cancel="handleDesensDialogCancel"
    />
  </a-modal>
</template>
<script>
import modalMixin from '@/utils/modal.mixin'
import clonedeep from 'lodash.clonedeep'
import { applyTax } from '@api/cost/audit'
import { apiMosaicUploadNew } from '@api/cost/cost'
import DesensitizationModal from '@views/cost-apply/components/desensitizationModal.vue'

// function getBase64 (file) {
//   return new Promise((resolve, reject) => {
//     const reader = new FileReader()
//     reader.readAsDataURL(file)
//     reader.onload = () => resolve(reader.result)
//     reader.onerror = error => reject(error)
//   })
// }
export default {
  mixins: [modalMixin],
  components: { DesensitizationModal },
  props: {
    auditStatus: {
      default: () => {},
      type: Object
    },
    applyNo: {
      type: String,
      default: undefined
    },
    oldStatus: {
      type: [String, Number],
      default: undefined
    },
    max: [Number, undefined]
  },
  data () {
    return {
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      confirmLoading: false,
      rules: {
        // 校验规则
        personalTax: [{ required: true, validator: this.moneyValidate, trigger: 'blur' }],
        approveDate: [{ required: true, message: this.$t('all.autotext845') }],
        taxUrl: [{ required: true, message: this.$t('all.autotext657'), trigger: 'blur' }],
        needApply: [{ required: true, message: this.$t('all.autotext1244'), trigger: 'blur' }]
      },
      needApply: 1,
      form: {
        personalTax: '',
        taxRemark: '',
        approveDate: '',
        taxUrl: '',
        fileArr: ''
      },
      previewVisible: false,
      previewImage: '',
      fileList: [],
      stopUpload: false,
      desensDialog: {
        type: 'edit',
        visible: false,
        originalFileUrl: '',
        afterFileUrl: '',
        selectRowIndex: 0,
        fileName: 'name'
      },
      uploading: false
    }
  },
  computed: {
    desensePassed () {
      const file = this.getUploadFile()
      const { afterUrl, originalUrl } = file || {}
      return afterUrl && afterUrl !== originalUrl
    }
  },
  watch: {
    auditStatus (newValue) {
      this.form.personalTax = clonedeep(newValue.personalTax) || ''
    }
  },
  methods: {
    moneyValidate (rule, value, callback) {
      if (!value || +value <= 0 || +value >= this.auditStatus.totalAmount) {
        callback(new Error(`申报金额需大于0且小于${this.auditStatus.totalAmount}`)) // eslint-disable-line
        return
      }
      callback()
    },
    // 校验图片格式是否符合要求
    beforeUpload (file) {
      const typeVal = file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/png'
      if (!typeVal) {
        this.$message.error(this.$t('all.autotext559'))
        this.stopUpload = true
      } else {
        this.stopUpload = false
      }
      return typeVal
    },
    // 校验金额为小数点后两位
    moneyCheck (val) {
      val = val.replace('e', '')
      val = val.replace(/[^0-9.]/g, '')
      val = val.replace(/^()*(\d+)\.(\d\d).*$/, '$1$2.$3') // 此处还可以限制位数以及大小
      return val
    },
    handleCancel () {
      this.previewVisible = false
    },
    async handlePreview () {
      const file = this.fileList[0]
      this.setDenseModalFile(file.originalUrl, file.afterUrl)
      this.desensDialog.visible = true
      this.desensDialog.type = 'preview'
    },
    async handleUpload ({ file }) {
      this.uploading = true
      try {
        const params = new FormData()
        params.append('file', file)
        const res = await apiMosaicUploadNew(params)
        res.name = file.name
        this.fileList.push(res)
        const { afterUrl, originalUrl } = res || {}
        this.form.taxUrl = afterUrl
        this.form.fileArr = JSON.stringify([
          {
            fileName: file.name,
            afterUrl,
            originalUrl,
            type: this.$const.UPLOAD_FILE_TYPE.TAX_RECEIPT.value
          }
        ])
        if (this.fileList.length > 1) {
          this.fileList = this.fileList.slice(-1)
        }
      } finally {
        this.uploading = false
      }
    },
    handleChange ({ file, fileList }) {
      if (this.stopUpload) {
        this.fileList = []
        return
      }
      this.fileList = fileList
      if (file.status === 'done') {
        if (file.response && file.response.data) {
          const { afterUrl, originalUrl } = file.response.data || {}
          this.form.taxUrl = afterUrl
          this.form.fileArr = JSON.stringify([
            {
              fileName: file.name,
              afterUrl,
              originalUrl,
              type: this.$const.UPLOAD_FILE_TYPE.TAX_RECEIPT.value
            }
          ])
          if (this.fileList.length > 1) {
            this.fileList = fileList.slice(-1)
          }
        } else {
          this.fileList = []
          this.$message.error(file.response.detail || this.$t('all.autotext1259'))
        }
      }
    },
    clickCancel () {
      this.needApply = 1
      this.form = {
        personalTax: '',
        taxRemark: '',
        approveDate: '',
        taxUrl: '',
        fileArr: ''
      }
      this.innerVisible = false
      this.$refs.ruleForm.resetFields()
      this.fileList = []
    },
    clickConfirm () {
      this.$refs.ruleForm.validate(async flag => {
        if (!flag) return
        let params = {}
        if (this.needApply === 1) {
          params = {
            id: this.$props.auditStatus.id,
            ...this.form
          }
        } else {
          params = {
            id: this.$props.auditStatus.id,
            personalTax: 0,
            taxRemark: this.form.taxRemark
          }
        }
        if (this.max && (params.personalTax > this.max)) {
          this.$message.error(this.$t('all.autotext1395'))
          return
        }
        this.confirmLoading = true
        try {
          await applyTax({
            applyNo: this.applyNo,
            oldStatus: this.oldStatus,
            ...params
          })
          this.confirmLoading = false
          this.$message.success(this.$t('all.autotext470'))
          this.clickCancel()
          this.$emit('ok')
        } catch (e) {
          this.confirmLoading = false
        }
      })
    },
    getUploadFile () {
      if (!this.fileList.length) return null
      return this.fileList[0]
    },
    /**
     * 设置脱敏弹窗的文件
     * @param fileUrl 原始文件 半路径
     * @param afterFileUrl 脱敏后文件 半路径
     */
    setDenseModalFile (fileUrl, afterFileUrl) {
      this.desensDialog.originalFileUrl = this.$options.filters.dealImageUrl(fileUrl)
      this.desensDialog.afterFileUrl = this.$options.filters.dealImageUrl(afterFileUrl)
    },
    editFile () {
      this.desensDialog.type = 'edit'
      const file = this.getUploadFile()
      const { afterUrl, originalUrl } = file
      this.setDenseModalFile(originalUrl, afterUrl || originalUrl)
      this.desensDialog.fileName = file.name
      this.desensDialog.visible = true
      this.$nextTick(() => {
        this.$refs.desensitization.init()
      })
    },
    // 还原文件
    resetFile () {
      const selectRow = this.fileList[0]
      this.form.taxUrl = ''
      this.updateFormFileArr('')
      if (selectRow) {
        this.$set(selectRow, 'afterUrl', '')
      }
      this.editFile()
    },
    deleteFile () {
      this.fileList = []
      this.form.taxUrl = ''
      this.form.fileArr = ''
    },
    updateFormFileArr (fileUrl) {
      if (!this.form.fileArr) return
      const currentFileArr = JSON.parse(this.form.fileArr)
      const newFileArr = currentFileArr.map(e => ({
        ...e,
        afterUrl: fileUrl
      }))
      this.form.fileArr = JSON.stringify(newFileArr)
    },
    handleDesensDialogOk (fileUrl) {
      const file = this.getUploadFile()
      this.form.taxUrl = fileUrl
      this.updateFormFileArr(fileUrl)
      const updatedFile = {
        ...file,
        afterUrl: fileUrl
      }
      this.fileList = [updatedFile]
    },
    handleDesensDialogCancel () {
      this.desensDialog = {
        type: 'edit',
        visible: false,
        originalFileUrl: '',
        afterFileUrl: '',
        selectRowIndex: 0,
        fileName: 'name'
      }
    }
  }
}
</script>
<style lang="less" scoped>
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.upload-tax-item {
  /deep/ .ant-upload-list {
    .ant-upload-list-picture-card-container,.ant-upload-list-item {
      width: 240px;
      height: 130px;
    }
  }
  .upload-btn {

  }
}
</style>
